<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/13 0013
 * Time: 13:29
 */

namespace app\admin\controller;

use think\Db;
use app\admin\model\Goods as GoodsModel;
use app\admin\model\Taoorder as TaoorderModel;

class Taoorder extends Common
{
    /**
     * 订单列表
     * @return array|mixed|\think\response\View
     * @throws \think\exception\DbException
     */
    public function index()
    {

        $TaoorderMd = new TaoorderModel();
        $ks=input('ks');
        $TaoorderList = $TaoorderMd->order('establish_time desc')->where('item_title','like','%'.$ks.'%')->paginate(15,false,$config = ['query'=>array('ks'=>$ks)]);
        foreach($TaoorderList as $taoKey=>$taoVal){
            switch ($taoVal['tk_status']) {
                case 3 : $TaoorderList[$taoKey]['tk_status'] = '订单结算';break;
                case 12 : $TaoorderList[$taoKey]['tk_status'] = '订单付款';break;
                case 13 : $TaoorderList[$taoKey]['tk_status'] = '订单失效';break;
                case 14 : $TaoorderList[$taoKey]['tk_status'] = '订单收货';break;
            }
        }
        $this->assign('TaoorderList', $TaoorderList);
        return view();
    }

    /**
     * 查询导入订单
     * @return array|mixed|\think\response\Json|\think\response\View
     */
    public function add()
    {
        if(request()->isPost()){
            $start_time = input("post.start_time");//开始时间
            $end_time = input("post.end_time");//结束时间
            $payStatus = intval(input("post.payStatus"));//创建时间=1，结算时间=3
            $toPage = intval(input("post.toPage"));//页数

            if(empty($start_time)){
                return json(['code'=>202,'msg'=>'请选中开始查询时间']);
            }
            if(empty($end_time)){
                return json(['code'=>202,'msg'=>'请选中结束查询时间']);
            }
            if(empty($payStatus)){
                $payStatus = '';
                $queryType = 1;
            }else{
                $queryType = $payStatus;
            }
            if(empty($toPage)){
                return json(['code'=>202,'msg'=>'页数值姿势错误']);
            }

            $res = $this->collection($start_time,$end_time,$payStatus,$queryType,$toPage);
            if($res['code'] == 202){
                return json($res);
            }
            return json($res);

        }
        return view();
    }

    public function collection($start_time,$end_time,$payStatus,$queryType,$toPage)
    {

        if($this->islogin() == false){
            return ['code'=>202,'msg'=>'请登录阿里妈妈获取cookie后再来采集吧！'];
        }
        $token = "353fbb3b63af9";//token

        $tOrderList = [];
        for($page_no=1;$page_no<=$toPage;$page_no++) {
            $url = "https://pub.alimama.com/report/getTbkPaymentDetails.json?startTime=".$start_time."&endTime=".$end_time."&payStatus=".$payStatus."&queryType=".$queryType."&toPage=".$page_no."&perPageSize=20&total=&t=1536848131734&pvid=&_tb_token_=".$token."&_input_charset=utf-8";
            $taoorder = $this->getHttpRequestWith($url);
            if($taoorder['ok'] == false){
                return ['code'=>202,'msg'=>$taoorder['info']['message']];
            }else{
                foreach($taoorder['data']['paymentList'] as $item){
                    array_push($tOrderList,$item);
                }
            }
        }
        $insertNum = 0;//新增订单数量
        $updateNum = 0;//更新订单数量

        foreach($tOrderList as $tOrderItem){
            $data = [
                'alipay_total_price' => $tOrderItem['totalAlipayFeeString'],//付款金额
                'tk_status' => $tOrderItem['payStatus'],//淘客订单状态
                'tk3rd_type' => $tOrderItem['tk3rdTypeStr'],//第三方服务来源，没有第三方服务，取值为“--”
                'item_title' => $tOrderItem['auctionTitle'],//商品名称
                'seller_shop_title' => $tOrderItem['exShopTitle'],//店铺名称
                'pay_price' => $tOrderItem['realPayFeeString'],//实际付款金额
                'item_num' => $tOrderItem['auctionNum'],//商品数量
                'trade_id' => $tOrderItem['taobaoTradeParentId'],//订单号
                'seller_nick' => $tOrderItem['exNickName'],//掌柜名称
                'total_commission_fee' => $tOrderItem['tkPubShareFeeString'],//佣金金额
                'terminal_type' => $tOrderItem['terminalType'],//成交平台，PC，无线
                'total_commission_rate' => $tOrderItem['discountAndSubsidyToString'],//佣金比率
                'auctionUrl' => $tOrderItem['auctionUrl'],//商品链接
                'tkAlimmShareRate' => $tOrderItem['tkAlimmShareRate'],//技术服务费比率
                'create_time' => $tOrderItem['createTime'],//淘客订单创建时间
                'earning_time' => $tOrderItem['earningTime'],//淘客订单结算时间
                'tao_user_id2' => substr($tOrderItem['taobaoTradeParentId'],-6,2),//淘宝下单用户id、15-16位买家ID的倒数1-2位
                'tao_user_id4' => substr($tOrderItem['taobaoTradeParentId'],-4,4),//淘宝下单用户id、17-18位买家ID的倒数3-4位
            ];
            $taoorder_id = TaoorderModel::where('trade_id',$data['trade_id'])->value('id');
            if($taoorder_id){
                $item = [
                    'alipay_total_price' => $data['alipay_total_price'],//付款金额
                    'pay_price' => $data['pay_price'],//实际付款金额
                    'tk_status' => $data['tk_status'],//订单状态
                    'earning_time' => $data['earning_time'],//结算时间
                ];
                $tid = TaoorderModel::edit($taoorder_id,$item);
                unset($data);
                if($tid){
                    $updateNum += 1;
                }else{
                    return ['code'=>202,'msg'=>'入库订单更新失败，请稍后再试！'];
                }
            }else{
                $tid = TaoorderModel::add($data);
                unset($data);
                if($tid){
                    $insertNum += 1;
                }else{
                    return ['code'=>202,'msg'=>'添加入库订单失败，请稍后再试！'];
                }
            }
        }
        return ['code'=>200,'msg'=>'添加入库订单'.$insertNum.'件、更新入库订单'.$updateNum.'件'];

    }
}